package cn.harry.modular.sys.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.common.utils.SecurityUtils;
import cn.harry.modular.sys.domain.SysUser;
import cn.harry.modular.sys.param.SysUserUpdateIconParam;
import cn.harry.modular.sys.param.SysUserUpdatePasswordParam;
import cn.harry.modular.sys.service.SysUserService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * ClassName: SysProfileController Description:
 *
 * @author honghh Date 2020/04/29 13:42 Copyright (C) www.tech-harry.cn
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "sys-user-profile 后台用户管理")
@RequestMapping("/sys/user/profile")
public class SysProfileController {

	private final SysUserService sysUserService;

	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	@Operation(summary = "获取当前登录的个人信息")
	@GetMapping
	public R<SysUser> getPersonalInfo() {
		return R.success(SecurityUtils.getSysUser());
	}

	@Operation(summary = "修改指定用户信息")
	@SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public R<Integer> update(@RequestBody SysUser user) {
		// 更新用户信息 获取当前用户信息
		SysUser currentUser = SecurityUtils.getSysUser();
		// 仅允许当前登录的用户 手机号码、邮箱、性别等信息
		return sysUserService.update(currentUser.getId(), user) > 0 ? R.success()
				: R.failed();
	}

	@Operation(summary = "updatePassword 修改密码")
	@PutMapping(value = "/updatePassword")
	public R<Integer> updatePassword(
			@RequestBody SysUserUpdatePasswordParam passwordParam) {
		Long userId = SecurityUtils.getUserId();
		SysUser dbUser = sysUserService.getById(userId);
		if (!ENCODER.matches(passwordParam.getOldPassword(), dbUser.getPassword())) {
			return R.failed("原密码不正确");
		}
		// 新密码
		String newPass = ENCODER.encode(passwordParam.getNewPassword());
		// 更新密码
		return sysUserService.updatePasswordByUserId(userId, newPass) ? R.success()
				: R.failed();
	}

	@Operation(summary = "avatar 用户头像上传")
	@SysLog(title = "用户头像上传", businessType = BusinessType.UPDATE)
	@PostMapping("/avatar")
	public R<Integer> avatar(@RequestBody SysUserUpdateIconParam param) {
		// 更新用户信息 获取当前用户信息
		SysUser currentUser = SecurityUtils.getSysUser();
		currentUser.setIcon(param.getIcon());
		// 仅允许当前登录的用户 手机号码、邮箱、性别等信息
		return sysUserService.update(currentUser.getId(), currentUser) > 0 ? R.success()
				: R.failed();
	}

}
